<?php

namespace App\Supports\Payment\Channels;

use Exception;
use Monolog\Logger;
use Yansongda\Pay\Pay;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use App\Supports\Payment\Contracts\Channel;
use App\Supports\Payment\Contracts\PayChannel;

class WxPay extends Channel implements PayChannel
{
	public function __construct()
	{
		$this->channelName = 'wxpay';
		$this->setConfig();
		$this->setOrigin();
	}

	public function setConfig()
	{
		$route = config('wxpay.default');

		$action = $this->getRouteAction();
		if ($action == 'payOrderByWxwap') {

			$this->config = config("wxpay.TTWRT_PLATFORM");
		}else{

			$this->config = config("wxpay.TTWRT");
		}
		
	}

	public function setOrigin()
	{
		$config = $this->config;
		$config['notify_url'] = route('web.payments.wxpay.notify');

		if (app()->environment('production')) {
			$config['log']['level'] = Logger::WARNING;
		} else {
			$config['log']['level'] = Logger::DEBUG;
		}
		$this->origin = Pay::wechat($config);
	}

	public function tools($data = null)
	{
		// TODO: Implement tools() method.
	}

	public function getChannelName()
	{
		return $this->channelName;
	}

	public function getRouteAction()
	{
		$routeAction = explode('@', Route::currentRouteAction());
		$action = $routeAction[1];
		return $action;
	}

	public function verify($data = null)
	{
		$action = $this->getRouteAction();

		if ($action == 'wxpayRefundNotify') {
			return $this->origin->verify(null, true);
		}
		return $this->origin->verify();
	}

	public function find($data = null)
	{
		// TODO: Implement find() method.
	}

	public function pay($data = null)
	{
		try {
			$action = $this->getRouteAction();
			if ($action == 'payOrderByWxwap') {
				//dd($this->origin->wap($data)->send());

				/*var_dump($this->origin);
				dd($data);*/
				return $this->origin->mp($data);
				/*$response = $this->origin->wap($data);
				$res = ['code_url'=>$response->getTargetUrl()];
				return $res;*/
			}
			return $this->origin->app($data)->send();
		} catch (Exception $exception) {
			$message = $exception->getCode().$exception->getMessage();
			throw new Exception($message);
		}
	}

	public function refund($data = null)
	{
		try {
			return $this->origin->refund($data);
		} catch (Exception $exception) {
			$message = $exception->getCode().$exception->getMessage();
			throw new Exception($message);
		}
	}

	public function transfer($data = null)
	{
		try {
			return $this->origin->transfer($data);
		} catch (Exception $exception) {
			$message = $exception->getCode().$exception->getMessage();
			throw new Exception($message);
		}
	}

	public function query($data = null)
	{
		// TODO: Implement query() method.
	}

	public function success()
	{
		return $this->origin->success();
	}
}
